package com.shuang.interceptors;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.shuang.common.JsonUtils;
import com.shuang.redis.JedisClient;
/**
 * 前台未登录拦截
 * @author shuang
 * Created by shuang on 2016/11/20.
 */
public class LimitsFrontInterceptors implements HandlerInterceptor {
	
	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY ;
	
	@Value("${REDIS_SESSION_EXPIRE}")
	private Integer REDIS_SESSION_EXPIRE;
	
	@Resource(name="jedisClient")
	private JedisClient jedisClient;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		Cookie[] cookies = request.getCookies();
		if(cookies!=null&&cookies.length>1){
			for(Cookie cookie :cookies){
				if((cookie.getName()!=null&&cookie.getName().equals("FRONT_SESSION_KEY"))){//前台
					String token=cookie.getValue();
					String jsonStr=jedisClient.get(REDIS_USER_SESSION_KEY+":"+token);
					if(jsonStr!=""&&jsonStr!=null){
						return true;
					}
				}
			}
		}
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("status", "403");
		map.put("data", "请先登录");
		response.getWriter().print(JsonUtils.objectToJson(map));
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}
}
